package com.chonor.mall.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClient;
import com.chonor.mall.config.OssConfig;
import com.chonor.mall.service.UploadService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@Service
@Slf4j
public class UploadServiceImpl implements UploadService {

    @Value("${aliyun.oss.policy.expire}")
    private int ALIYUN_OSS_EXPIRE;
    @Value("${aliyun.oss.maxSize}")
    private int ALIYUN_OSS_MAX_SIZE;
    @Value("${aliyun.oss.callback}")
    private String ALIYUN_OSS_CALLBACK;
    @Value("${aliyun.oss.bucketName}")
    private String ALIYUN_OSS_BUCKET_NAME;
    @Value("${aliyun.oss.endpoint}")
    private String ALIYUN_OSS_ENDPOINT;
    @Value("${aliyun.oss.dir.prefix}")
    private String ALIYUN_OSS_DIR_PREFIX;
    @Value("${aliyun.oss.accessKeyId}")
    private String ALIYUN_OSS_ACCESSKEYID;
    @Value("${aliyun.oss.accessKeySecret}")
    private String ALIYUN_OSS_ACCESSKEYSECRET;

    @Override
    public String uploadFile(MultipartFile file) {
        // 读取图片
        // 生成文件目录
        String format = new SimpleDateFormat("yyyy/MM/dd").
                format(new Date());
        String uuid = UUID.randomUUID().toString().replace("-", "");
        String originName = uuid + file.getName();
        String fileName = format + "/" + originName;
        OSS ossClient = null;
        try {
            ossClient = new OSSClient(ALIYUN_OSS_ENDPOINT,ALIYUN_OSS_ACCESSKEYID,ALIYUN_OSS_ACCESSKEYSECRET);
            InputStream inputStream = file.getInputStream();
            ossClient.putObject(ALIYUN_OSS_BUCKET_NAME, fileName, inputStream);
            ossClient.shutdown();
            String url = "https://" + ALIYUN_OSS_BUCKET_NAME + "." + ALIYUN_OSS_ENDPOINT + "/" + fileName;
            return url;
        } catch (Exception e) {
            log.error(e.getMessage());
        }
        return null;
    }
}
